# coding=utf-8
"""
作者：董新强 
创建时间：2020-4-10
描述：权限助手
"""
import json

from tornado.gen import coroutine
from tornado.httpclient import AsyncHTTPClient

from framework.aes_cypto import AesCrypto
from framework.utilities import to_dict, to_int, get_random_chars, to_sha256
from setting import AUTH_VALIDATE_URI


class AuthHelper():
    def __init__(self):
        self._app_id = r'ee94a3106a5411eaa18114dda9040cae'
        self._app_key = r'inHbwmfW8Yl6hLEMuRsCeZ3TtF9ID2az0gk4NGK5U1y'
        self._random_str = get_random_chars(letter_only=True)
        self._check = to_sha256(''.join([self._app_id, self._app_key, self._random_str]))

    def gen_post_body(self, key, value):
        return {'id': self._app_id, 'check': self._check, 'rand': self._random_str, key: value}

    @coroutine
    def validate(self, token):
        """
        验证用户登录token
        :param token: 用户登录所用token
        :return:
        """
        url = '%stoken' % (AUTH_VALIDATE_URI,)
        http_client = AsyncHTTPClient()
        response = yield http_client.fetch(url, method='POST', body=json.dumps(self.gen_post_body('token', token)))

        if not response:
            return False, '请登录'

        response = to_dict(response.body)
        if not response['code']:
            return False, response.get('msg')

        return True, to_dict(AesCrypto(self._app_key).decrypt(response['data']))

    @coroutine
    def get_user(self, phone):
        """
        获取指定电话号码的用户
        :param phone: 电话号码
        """
        url = '%suser/get' % (AUTH_VALIDATE_URI,)
        http_client = AsyncHTTPClient()
        response = yield http_client.fetch(url, method='POST', body=json.dumps(self.gen_post_body('phone', phone)))

        if not response:
            return False, '请登录'

        response = to_dict(response.body)
        if not response['code']:
            return False, response.get('msg')

        return True, to_dict(AesCrypto(self._app_key).decrypt(response['data']))

    @coroutine
    def get_create_uid(self, phone):
        """
        创建指定电话号码用户
        :param phone: 电话号码
        """
        url = '%suser/create' % (AUTH_VALIDATE_URI,)
        http_client = AsyncHTTPClient()
        response = yield http_client.fetch(url, method='POST', body=json.dumps(self.gen_post_body('phone', phone)))

        if not response:
            return False, '请登录'

        response = to_dict(response.body)
        if not response['code']:
            return False, response.get('msg')

        return True, to_int(AesCrypto(self._app_key).decrypt(response['data']))

    @coroutine
    def login_with_wx_open_id(self, wx_open_id):
        """
        根据openid获取(或创建)用户
        :param wx_open_id: 微信open_id
        """
        url = '%slogin/wx' % (AUTH_VALIDATE_URI,)
        http_client = AsyncHTTPClient()
        response = yield http_client.fetch(url, method='POST', body=json.dumps(self.gen_post_body('openid', wx_open_id)))

        if not response:
            return False, 0, '请登录'

        response = to_dict(response.body)
        if not response['code']:
            return False, 0, response.get('msg')

        dic = to_dict(AesCrypto(self._app_key).decrypt(response['data']))
        return True, dic['uid'], dic['token']

    @coroutine
    def get_login_token(self, uid):
        """
        获取用户登录通ken
        """
        url = '%slogin' % (AUTH_VALIDATE_URI,)
        http_client = AsyncHTTPClient()
        response = yield http_client.fetch(url, method='POST', body=json.dumps(self.gen_post_body('uid', uid)))

        if not response:
            return False, '请登录'

        response = to_dict(response.body)
        if not response['code']:
            return False, response.get('msg')

        return True, AesCrypto(self._app_key).decrypt(response['data'])


if __name__ == '__main__':
    from tornado.ioloop import IOLoop


    @coroutine
    def run():
        inst = AuthHelper()
        result = yield inst.get_user(18314392056)
        print(result)

        result = yield inst.get_create_uid(17787112873)
        print(result)

        # result = yield inst.get_login_token(1351)
        # print(result)

        result = yield inst.validate('Token Mjq3FmXaEaYkECYvvSvUOTO5JNI6AizKKPkvxhtdI4pd2Aa0Gfn8BIgtPV0P5FbjZiBvY54Nw29ykGqDVbBybw3udfo3lVvjHsznlsOtvZ4gMANgD79E6BBkVlWul6io')
        print(result)


    IOLoop.current().run_sync(run)
